/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: pm8.8.zero.c
> Author:
> Mail: 
> Created Time: Thu 08 Aug 2024 01:42:52 AM PDT
***************************************************/

 //修改案例ex4.c,将两个信号量和全局变量封装，实现为局部变量。


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

typedef struct memssage
{
	sem_t semr;
	sem_t semw;
	int data;
}mem;

void *fun1(void *arg)
{
	mem *p = (mem*)arg;
	while(1)
	{
		sem_wait(&p->semw);
		p->data = p->data + 1;
		sem_post(&p->semr);
	}

}

void *fun2(void *arg)
{ 
	mem* p =(mem*)arg;
	while(1)
	{
		sem_wait(&p->semr);
		printf("data = %d\n",p->data);
		sem_post(&p->semw);
	}
}

int main(int argc,const char* argv[])
{
	pthread_t tid1 = 0,tid2 = 0;
	int ret = 0;
	mem p;
	memset(&p,0,sizeof(mem));
	sem_init(&p.semw,0,1);
	sem_init(&p.semr,0,0);


	ret = pthread_create(&tid1,NULL,fun1,&p);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}
	ret = pthread_create(&tid2,NULL,fun2,&p);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);

	sem_destroy(&p.semr);
	sem_destroy(&p.semw);
	return 0;
}
